"use client"

import { useState, useEffect } from "react"
import { Button } from "@/components/ui/button"
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card"
import { Badge } from "@/components/ui/badge"
import { Input } from "@/components/ui/input"
import { Textarea } from "@/components/ui/textarea"
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select"
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogFooter,
  DialogHeader,
  DialogTitle,
  DialogTrigger,
} from "@/components/ui/dialog"
import {
  CheckCircle,
  XCircle,
  Clock,
  Play,
  Users,
  Package,
  FileText,
  Plus,
  Edit,
  Trash2
} from "lucide-react"

interface TestStep {
  id: string
  name: string
  description: string
  status: 'pending' | 'running' | 'completed' | 'failed'
  result?: string
  error?: string
  data?: any
}

interface Project {
  id: string
  projectTitle: string
  projectCode: string
  name: string
  level1: string
  level2: string
  statusDesc: string
  priority: string
  createTime: string
}

interface TeamMember {
  id: string
  name: string
  email: string
  role: string
  status: string
}

interface Sample {
  id: string
  sampleName: string
  sampleCode: string
  status: string
  quantity: number
  unit: string
}

export default function TestFlowPage() {
  const [steps, setSteps] = useState<TestStep[]>([
    {
      id: '1',
      name: '创建项目',
      description: '创建一个新的研究项目',
      status: 'pending'
    },
    {
      id: '2',
      name: '更新项目状态',
      description: '将项目状态从草稿更新为进行中',
      status: 'pending'
    },
    {
      id: '3',
      name: '添加团队成员',
      description: '为项目添加团队成员',
      status: 'pending'
    },
    {
      id: '4',
      name: '添加样品',
      description: '为项目添加测试样品',
      status: 'pending'
    },
    {
      id: '5',
      name: '查看历史记录',
      description: '验证项目历史记录是否完整',
      status: 'pending'
    }
  ])

  const [currentStep, setCurrentStep] = useState(0)
  const [isRunning, setIsRunning] = useState(false)
  const [createdProject, setCreatedProject] = useState<Project | null>(null)
  const [teamMembers, setTeamMembers] = useState<TeamMember[]>([])
  const [samples, setSamples] = useState<Sample[]>([])
  const [histories, setHistories] = useState<any[]>([])

  const updateStepStatus = (stepId: string, status: TestStep['status'], result?: string, error?: string, data?: any) => {
    setSteps(prev => prev.map(step => 
      step.id === stepId ? { ...step, status, result, error, data } : step
    ))
  }

  const runTestFlow = async () => {
    setIsRunning(true)
    setCurrentStep(0)

    // 重置所有步骤状态
    setSteps(prev => prev.map(step => ({ ...step, status: 'pending', result: undefined, error: undefined, data: undefined })))
    setCreatedProject(null)
    setTeamMembers([])
    setSamples([])
    setHistories([])

    // 步骤1: 创建项目
    setCurrentStep(0)
    updateStepStatus('1', 'running')
    try {
      const projectData = {
        projectTitle: '测试项目-' + Date.now(),
        name: '测试项目名称',
        projectCode: 'TEST-' + Date.now(),
        projectType: 'research',
        category: '测试分类',
        description: '这是一个用于测试流程的项目',
        customerName: '测试客户',
        applicantName: '测试申请人',
        projectManagerName: '测试经理',
        priority: 'MEDIUM',
        startDate: new Date().toISOString().split('T')[0],
        endDate: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString().split('T')[0],
        createdBy: 'test-user'
      }

      const response = await fetch('/api/projects', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(projectData)
      })

      if (response.ok) {
        const project = await response.json()
        setCreatedProject(project)
        updateStepStatus('1', 'completed', `项目创建成功: ${project.projectTitle}`, undefined, project)
      } else {
        const error = await response.json()
        updateStepStatus('1', 'failed', undefined, error.error || '创建项目失败')
      }
    } catch (error) {
      updateStepStatus('1', 'failed', undefined, error instanceof Error ? error.message : '创建项目时发生错误')
    }

    await new Promise(resolve => setTimeout(resolve, 1000))

    // 步骤2: 更新项目状态
    setCurrentStep(1)
    updateStepStatus('2', 'running')
    try {
      if (!createdProject) {
        throw new Error('没有可用的项目')
      }

      const statusData = {
        level1: 'IN_PROGRESS',
        level2: '开发阶段',
        statusDesc: '项目已进入开发阶段',
        updatedBy: 'test-user',
        comment: '状态更新测试'
      }

      const response = await fetch(`/api/projects/${createdProject.id}/status`, {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(statusData)
      })

      if (response.ok) {
        const updatedProject = await response.json()
        updateStepStatus('2', 'completed', `状态更新成功: ${updatedProject.level1}`, undefined, updatedProject)
      } else {
        const error = await response.json()
        updateStepStatus('2', 'failed', undefined, error.error || '更新状态失败')
      }
    } catch (error) {
      updateStepStatus('2', 'failed', undefined, error instanceof Error ? error.message : '更新状态时发生错误')
    }

    await new Promise(resolve => setTimeout(resolve, 1000))

    // 步骤3: 添加团队成员
    setCurrentStep(2)
    updateStepStatus('3', 'running')
    try {
      if (!createdProject) {
        throw new Error('没有可用的项目')
      }

      const memberData = {
        name: '测试成员',
        email: 'test@example.com',
        phone: '13800138000',
        department: '测试部门',
        position: '测试工程师',
        role: 'MEMBER',
        status: 'ACTIVE',
        responsibilities: '负责测试工作',
        skills: ['测试', '开发'],
        createdBy: 'test-user'
      }

      const response = await fetch(`/api/projects/${createdProject.id}/team`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(memberData)
      })

      if (response.ok) {
        const member = await response.json()
        setTeamMembers([member])
        updateStepStatus('3', 'completed', `团队成员添加成功: ${member.name}`, undefined, member)
      } else {
        const error = await response.json()
        updateStepStatus('3', 'failed', undefined, error.error || '添加团队成员失败')
      }
    } catch (error) {
      updateStepStatus('3', 'failed', undefined, error instanceof Error ? error.message : '添加团队成员时发生错误')
    }

    await new Promise(resolve => setTimeout(resolve, 1000))

    // 步骤4: 添加样品
    setCurrentStep(3)
    updateStepStatus('4', 'running')
    try {
      if (!createdProject) {
        throw new Error('没有可用的项目')
      }

      const sampleData = {
        sampleName: '测试样品',
        sampleCode: 'TS-001',
        sampleType: 'material',
        description: '用于测试的样品',
        quantity: 5,
        unit: '个',
        status: 'PENDING',
        location: '实验室A-01',
        receivedDate: new Date().toISOString(),
        createdBy: 'test-user'
      }

      const response = await fetch(`/api/projects/${createdProject.id}/samples`, {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(sampleData)
      })

      if (response.ok) {
        const sample = await response.json()
        setSamples([sample])
        updateStepStatus('4', 'completed', `样品添加成功: ${sample.sampleName}`, undefined, sample)
      } else {
        const error = await response.json()
        updateStepStatus('4', 'failed', undefined, error.error || '添加样品失败')
      }
    } catch (error) {
      updateStepStatus('4', 'failed', undefined, error instanceof Error ? error.message : '添加样品时发生错误')
    }

    await new Promise(resolve => setTimeout(resolve, 1000))

    // 步骤5: 查看历史记录
    setCurrentStep(4)
    updateStepStatus('5', 'running')
    try {
      if (!createdProject) {
        throw new Error('没有可用的项目')
      }

      const response = await fetch(`/api/projects/${createdProject.id}/histories`)
      if (response.ok) {
        const historyData = await response.json()
        setHistories(Array.isArray(historyData) ? historyData : [])
        updateStepStatus('5', 'completed', `历史记录获取成功: ${historyData.length} 条记录`, undefined, historyData)
      } else {
        const error = await response.json()
        updateStepStatus('5', 'failed', undefined, error.error || '获取历史记录失败')
      }
    } catch (error) {
      updateStepStatus('5', 'failed', undefined, error instanceof Error ? error.message : '获取历史记录时发生错误')
    }

    setIsRunning(false)
  }

  const getStatusIcon = (status: TestStep['status']) => {
    switch (status) {
      case 'pending':
        return <Clock className="h-5 w-5 text-gray-400" />
      case 'running':
        return <Play className="h-5 w-5 text-blue-500" />
      case 'completed':
        return <CheckCircle className="h-5 w-5 text-green-500" />
      case 'failed':
        return <XCircle className="h-5 w-5 text-red-500" />
    }
  }

  const getStatusColor = (status: TestStep['status']) => {
    switch (status) {
      case 'pending':
        return 'bg-gray-100 text-gray-800'
      case 'running':
        return 'bg-blue-100 text-blue-800'
      case 'completed':
        return 'bg-green-100 text-green-800'
      case 'failed':
        return 'bg-red-100 text-red-800'
    }
  }

  return (
    <div className="container mx-auto p-6 space-y-6">
      <div className="text-center">
        <h1 className="text-3xl font-bold mb-2">研发管理流程测试</h1>
        <p className="text-gray-600">测试整个研发项目生命周期管理系统的核心功能</p>
      </div>

      {/* 控制面板 */}
      <Card>
        <CardHeader>
          <CardTitle>测试控制</CardTitle>
        </CardHeader>
        <CardContent>
          <div className="flex items-center justify-between">
            <div>
              <p className="text-sm text-gray-600">
                点击开始按钮运行完整的测试流程，验证所有核心功能是否正常工作
              </p>
            </div>
            <Button 
              onClick={runTestFlow} 
              disabled={isRunning}
              className="flex items-center gap-2"
            >
              <Play className="h-4 w-4" />
              {isRunning ? '测试中...' : '开始测试'}
            </Button>
          </div>
        </CardContent>
      </Card>

      {/* 测试步骤 */}
      <div className="space-y-4">
        {steps.map((step, index) => (
          <Card key={step.id} className={index === currentStep && isRunning ? 'border-blue-500' : ''}>
            <CardContent className="p-4">
              <div className="flex items-start gap-4">
                <div className="flex-shrink-0 mt-1">
                  {getStatusIcon(step.status)}
                </div>
                <div className="flex-1">
                  <div className="flex items-center gap-2 mb-2">
                    <h3 className="font-semibold">{step.name}</h3>
                    <Badge className={getStatusColor(step.status)}>
                      {step.status === 'pending' && '等待中'}
                      {step.status === 'running' && '运行中'}
                      {step.status === 'completed' && '已完成'}
                      {step.status === 'failed' && '失败'}
                    </Badge>
                  </div>
                  <p className="text-sm text-gray-600 mb-2">{step.description}</p>
                  
                  {step.result && (
                    <div className="text-sm text-green-600 bg-green-50 p-2 rounded">
                      {step.result}
                    </div>
                  )}
                  
                  {step.error && (
                    <div className="text-sm text-red-600 bg-red-50 p-2 rounded">
                      {step.error}
                    </div>
                  )}
                </div>
              </div>
            </CardContent>
          </Card>
        ))}
      </div>

      {/* 测试结果 */}
      {(createdProject || teamMembers.length > 0 || samples.length > 0 || histories.length > 0) && (
        <div className="grid grid-cols-1 md:grid-cols-2 gap-6">
          {/* 项目信息 */}
          {createdProject && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="h-5 w-5" />
                  创建的项目
                </CardTitle>
              </CardHeader>
              <CardContent className="space-y-2">
                <div><strong>项目标题:</strong> {createdProject.projectTitle}</div>
                <div><strong>项目编码:</strong> {createdProject.projectCode}</div>
                <div><strong>状态:</strong> {createdProject.level1}</div>
                <div><strong>优先级:</strong> {createdProject.priority}</div>
                <div><strong>创建时间:</strong> {new Date(createdProject.createTime).toLocaleString()}</div>
              </CardContent>
            </Card>
          )}

          {/* 团队成员 */}
          {teamMembers.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Users className="h-5 w-5" />
                  团队成员
                </CardTitle>
              </CardHeader>
              <CardContent>
                {teamMembers.map(member => (
                  <div key={member.id} className="space-y-1">
                    <div><strong>姓名:</strong> {member.name}</div>
                    <div><strong>邮箱:</strong> {member.email}</div>
                    <div><strong>角色:</strong> {member.role}</div>
                    <div><strong>状态:</strong> {member.status}</div>
                  </div>
                ))}
              </CardContent>
            </Card>
          )}

          {/* 样品信息 */}
          {samples.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <Package className="h-5 w-5" />
                  样品信息
                </CardTitle>
              </CardHeader>
              <CardContent>
                {samples.map(sample => (
                  <div key={sample.id} className="space-y-1">
                    <div><strong>样品名称:</strong> {sample.sampleName}</div>
                    <div><strong>样品编码:</strong> {sample.sampleCode}</div>
                    <div><strong>状态:</strong> {sample.status}</div>
                    <div><strong>数量:</strong> {sample.quantity} {sample.unit}</div>
                  </div>
                ))}
              </CardContent>
            </Card>
          )}

          {/* 历史记录 */}
          {histories.length > 0 && (
            <Card>
              <CardHeader>
                <CardTitle className="flex items-center gap-2">
                  <FileText className="h-5 w-5" />
                  历史记录 ({histories.length})
                </CardTitle>
              </CardHeader>
              <CardContent>
                <div className="space-y-2 max-h-40 overflow-y-auto">
                  {histories.slice(0, 5).map(history => (
                    <div key={history.id} className="text-sm p-2 bg-gray-50 rounded">
                      <div className="font-medium">{history.action}</div>
                      <div className="text-gray-600">{history.description}</div>
                      <div className="text-xs text-gray-500">
                        {new Date(history.createdAt).toLocaleString()}
                      </div>
                    </div>
                  ))}
                </div>
              </CardContent>
            </Card>
          )}
        </div>
      )}

      {/* 测试总结 */}
      {!isRunning && steps.some(step => step.status !== 'pending') && (
        <Card>
          <CardHeader>
            <CardTitle>测试总结</CardTitle>
          </CardHeader>
          <CardContent>
            <div className="grid grid-cols-1 md:grid-cols-3 gap-4">
              <div className="text-center">
                <div className="text-2xl font-bold text-green-600">
                  {steps.filter(s => s.status === 'completed').length}
                </div>
                <div className="text-sm text-gray-600">成功</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-red-600">
                  {steps.filter(s => s.status === 'failed').length}
                </div>
                <div className="text-sm text-gray-600">失败</div>
              </div>
              <div className="text-center">
                <div className="text-2xl font-bold text-blue-600">
                  {Math.round((steps.filter(s => s.status === 'completed').length / steps.length) * 100)}%
                </div>
                <div className="text-sm text-gray-600">成功率</div>
              </div>
            </div>
          </CardContent>
        </Card>
      )}
    </div>
  )
}